//
//  AppDelegate.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-5.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginController.h"
#import "LoginController.h"
#import "PioneerViewController.h"
#import "PPRevealSideViewController.h"
#import "LeveyTabBarController.h"
#import "LeftMenuTableViewController.h"
#import "CommunicationViewController.h"
#import "PartyNoticeViewController.h"
#import "PersonalViewController.h"
#import "PartyDataViewController.h"
#import "constant.h"
#import "PartyNoticeViewController.h"
#import "UPMainViewController.h"
#import "PersonalViewController.h"
#import "EaseMob.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "ApplyViewController.h"

#import "BPush.h"

#define BOUNDARY @"****"
#define TIMEOUT  (10*1000)
#define PREFIX  @"--"
#define LINE_END @"\r\n"
#define CONTENT_TYPE  @"multipart/form-data"

@interface AppDelegate()<PPRevealSideViewControllerDelegate,UINavigationControllerDelegate>{
    LeveyTabBarController * _tab;
    UINavigationController * _nav;
    BOOL _isFirstShow;
}
@end

@interface NSManagedObjectContext()
+ (void) MR_setDefaultContext:(NSManagedObjectContext *)moc;
+ (void) MR_setRootSavingContext:(NSManagedObjectContext *)context;
@end

@implementation AppDelegate
//@synthesize leveyTabBarController;
@synthesize faceView,mainVc,groupVC;
@synthesize  datas;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.requestQueue = [NSMutableArray array];
    self.totalBytesRcv = [NSMutableArray array];
    self.downloadController = [NSMutableArray array];
    //
    application.applicationIconBadgeNumber = 0;
    [Unread setUnreadNum:0 ForKey:kUnreadPioneerKey];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login) name:@"login" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout) name:@"logout" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(unreadChatMessageCountChange:) name:kNotificationUnreadChatMsgRefreshed object:nil];
    
    ///////////////CoreDate Init
    [MagicalRecord setupCoreDataStack];
    
    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    
    RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

    NSError *error = nil;
    BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error);
    if (! success) {
        RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error);
    }
    NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Store.sqlite"];
    NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];
    if (! persistentStore) {
        RKLogError(@"Failed adding persistent store at path '%@': %@", path, error);
    }
    
    [managedObjectStore createManagedObjectContexts];

    [NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:managedObjectStore.persistentStoreCoordinator];
    [NSManagedObjectContext MR_setRootSavingContext:managedObjectStore.persistentStoreManagedObjectContext];
    [NSManagedObjectContext MR_setDefaultContext:managedObjectStore.mainQueueManagedObjectContext];
    [PublicMethod refreshStaticCoreData];
    
    //运营商和时间的风格
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    //白色
    [[UINavigationBar appearance]setTintColor:[UIColor whiteColor]];
    
    if(IS_IOS7)[[UINavigationBar appearance]setBarTintColor:kNavigationBarColor];
    else [[UINavigationBar appearance] setTintColor:kNavigationBarColor];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    /*百度推送相关设置start*/
    [BPush setupChannel:launchOptions]; // 必须
    
    [BPush setDelegate:self]; // 必须。参数对象必须实现onMethod: response:方法，本示例中为self
    
    [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound];
    /*百度推送相关设置end*/
    
    /*环信相关设置start*/
//warning SDK注册 APNS文件的名字, 需要与后台上传证书时的名字一一对应
    NSString *apnsCertName = nil;
#if DEBUG
    apnsCertName = @"cdxf_ios_dev";
#else
    apnsCertName = @"cdxf_ios_production";
#endif
    // easemob-demo#chatdemoui   uestc-kb210#cdxf
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"uestc-kb210#cdxf" apnsCertName:apnsCertName];
#if DEBUG
    [[EaseMob sharedInstance] enableUncaughtExceptionHandler];
#endif
    [[[EaseMob sharedInstance] chatManager] setAutoFetchBuddyList:YES];
    //以下一行代码的方法里实现了自动登录，异步登录，需要监听[didLoginWithInfo: error:]
    //demo中此监听方法在MainViewController中
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
   /*环信相关设置end*/
    
    NSUserDefaults * defaultData = [NSUserDefaults standardUserDefaults];
    BOOL login = [defaultData boolForKey:@"login"];
    if (!login){
        LoginController *loginController  = [[LoginController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginController];
        nav.navigationBar.translucent=NO;
        self.window.rootViewController=nav;
        
        self.window.backgroundColor = [UIColor whiteColor];
        [self.window makeKeyAndVisible];
        return YES;
    }

   /*监测网络连接状态*/
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];
    

    [reach startNotifier];
    
    /**/
    
    //界面显示，监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationUnreadrefresh:) name:kNotificationUnreadChatMsgRefreshed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationUnreadrefresh:) name:kLoginNotifaction object:nil];
    
    _isFirstShow = NO;
    [self login];
    
    if(![constant checkAccount]){
        [self registerRemoteNotification];
        //初始化环信
        [self HXInitWithApplication:application options:launchOptions];
    }
    return YES;
}

#pragma mark 完成环信初始化工作
-(void)HXInitWithApplication:(UIApplication *)application options:(NSDictionary *)launchOptions{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    NSUserDefaults * defaultData = [NSUserDefaults standardUserDefaults];
    NSString * userPwd = [defaultData objectForKey:kMY_USER_PASSWORD];
    NSDictionary * ret = [[EaseMob sharedInstance].chatManager loginWithUsername:[constant getUserId] password:userPwd error:nil];
    NSLog(@"---ret---%@",ret);
    
#if DEBUG
    [[EaseMob sharedInstance] enableUncaughtExceptionHandler];
#endif
    [[[EaseMob sharedInstance] chatManager] setAutoFetchBuddyList:YES];
    
    //以下一行代码的方法里实现了自动登录，异步登录，需要监听[didLoginWithInfo: error:]
    //demo中此监听方法在MainViewController中
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
//warning 注册为SDK的ChatManager的delegate (及时监听到申请和通知)
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
//warning 如果使用MagicalRecord, 要加上这句初始化MagicalRecord
    //demo coredata, .pch中有相关头文件引用
    [MagicalRecord setupCoreDataStackWithStoreNamed:[NSString stringWithFormat:@"%@.sqlite", @"UIDemo"]];
    
    [self loginStateChange:nil];
    
}

- (void)registerRemoteNotification{
#if !TARGET_IPHONE_SIMULATOR
    UIApplication *application = [UIApplication sharedApplication];
    
    //iOS8 注册APNS 在ios8中，设置应用的application badge value需要得到用户的许可。
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
    
#endif
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#warning SDK方法调用
//    NSLog(@"error.description = %@",error.description);
    [[EaseMob sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注册推送失败"
//                                                    message:error.description
//                                                   delegate:nil
//                                          cancelButtonTitle:@"确定"
//                                          otherButtonTitles:nil];
//    [alert show];
}


/*06.15*/
-(void)reachabilityChanged:(NSNotification*)note
{
    
    Reachability * reach = [note object];
    NetworkStatus status =[reach currentReachabilityStatus];
    if([reach isReachable])
    {
//        NSLog(@"通知:网络正常!");
        switch (status) {
            case NotReachable:
                // 没有网络连接
//                [Alert showAlert:@"没有网络连接"];
                break;
            case ReachableViaWWAN:
                // 使用3G网络
//                [Alert showAlert:@"使用3G网络"];
                break;
            case ReachableViaWiFi:
                // 使用WiFi网络
//                [Alert showAlert:@"使用WiFi网络"];
                break;
        }
    }
    else
    {
        if (!_isFirstShow) {
           [Alert showAlert:@"网络异常"];
            _isFirstShow = YES;
        }
    }
}


/**/
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
//warning SDK方法调用
    [[EaseMob sharedInstance] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    if ([Unread getIsEnterFromRemote]) {
        //当应用是在有remote通知时是通过点击icon而不是点击通知进入时
        //此时1.用户进入应用后没有进入“通知公告”页面，者isEnterFromIcon = YES；也就是说用户没有读新的通知，因此icon的角标保留
        //   2.用户进入应用后点击进入了“通知公告”页面，此时不管他是不是真的看过新的通知，都认为他已经读了新消息，然后在通知页面将isEnterFromIcon设置为NO，因此去掉icon角标
        application.applicationIconBadgeNumber = 0;
    }
    [Unread setIsEnterFromRemote:NO];
    
//warning SDK方法调用
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
//    application.applicationIconBadgeNumber = 0;
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//warning SDK方法调用
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    if (![Unread getIsEnterFromRemote]) {
        [Unread setUnreadNum:application.applicationIconBadgeNumber ForKey:kUnreadPartyNoticeKey];
    }
    
//warning SDK方法调用
    [[EaseMob sharedInstance] applicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [MagicalRecord cleanUp];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
//warning SDK方法调用
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}

/***************************************************************************************/
/***************************************************************************************/
/***************************************************************************************/
/***************************************************************************************/
/***************************************************************************************/
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{

    [BPush registerDeviceToken:deviceToken]; // 必须
    [BPush bindChannel]; // 必须。可以在其它时机调用，只有在该方法返回（通过onMethod:response:回调）绑定成功时，app才能接收到Push消息。一个app绑定成功至少一次即可（如果access token变更请重新绑定)。
//    NSDictionary *dic = [constant getPersonalInfo];
//    NSString *branchNum = [dic objectForKey:@"branchNum"];
//    NSString *instituteNum = [dic objectForKey:@"institute"];
//    [BPush setTags:@[branchNum,instituteNum]];
    
//warning SDK方法调用
    [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}


// 必须，如果正确调用了setDelegate，在bindChannel之后，结果在这个回调中返回。
// 若绑定失败，请进行重新绑定，确保至少绑定成功一次  实现BPushDelegate协议，必须实现方法onMethod:response:
- (void) onMethod:(NSString*)method response:(NSDictionary*)data
{

//    if ([BPushRequestMethod_Bind isEqualToString:method])
//    {
//        NSDictionary* res = [[NSDictionary alloc] initWithDictionary:data];
//        
//        NSString *appid = [res valueForKey:BPushRequestAppIdKey];
//        NSString *userid = [res valueForKey:BPushRequestUserIdKey];
//        NSString *channelid = [res valueForKey:BPushRequestChannelIdKey];
//        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
//        NSString *requestid = [res valueForKey:BPushRequestRequestIdKey];
//    }
}

#pragma Remote Notification  在application: didReceiveRemoteNotification:中调用API，处理接收到的Push消息：



-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if (application.applicationState == UIApplicationStateActive) {
        NSLog(@"app active");
        int num = [[[userInfo objectForKey:@"aps"] objectForKey:@"badge"] intValue];
        [Unread setUnreadNum:num ForKey:kUnreadPartyNoticeKey];
        return;
    }
    
    [Unread setIsEnterFromRemote:YES];
    
    PartyNoticeViewController *partyNote = [[PartyNoticeViewController alloc] init];
    [_tab removeViewControllerAtIndex:0];
    [_tab setSelectedIndex:1];
    [partyNote willMoveToParentViewController:_tab];
    [_tab insertViewController:partyNote  atIndex:0];
    [self.revealSideViewController popViewControllerWithNewCenterController:[constant getCenterController] animated:YES];
    [_tab setSelectedIndex:0];
    [partyNote didMoveToParentViewController:[constant getCenterController]];


    application.applicationIconBadgeNumber = [[[userInfo objectForKey:@"aps"] objectForKey:@"badge"] intValue];
    application.applicationIconBadgeNumber = 0;
    
#warning SDK方法调用
    [[EaseMob sharedInstance] application:application didReceiveRemoteNotification:userInfo];
}
/***************************************************************************************/
/***************************************************************************************/
/***************************************************************************************/



#pragma Local Notification
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
#warning SDK方法调用
    [[EaseMob sharedInstance] application:application didReceiveLocalNotification:notification];
}






#pragma mark 设置可侧滑选项以及活动方向
- (PPRevealSideDirection)pprevealSideViewController:(PPRevealSideViewController *)controller directionsAllowedForPanningOnView:(UIView *)view{
    
    //@根据要求，除了首页，其他页面不能右滑
    if (_tab.selectedIndex){
        return NO;
    }
    return PPRevealSideDirectionRight|PPRevealSideDirectionLeft;
}

-(void)pprevealSideViewController:(PPRevealSideViewController *)controller panningHorizontally:(UIGestureRecognizer *)gesture{
    for (UIView *view in _tab.selectedViewController.view.subviews){
        if ([view isKindOfClass:[UIScrollView class]]){
            UIScrollView *sc=(UIScrollView*)view;
            [sc setScrollEnabled:NO];
        }
    }
}

-(void)pprevealSideViewController:(PPRevealSideViewController *)controller willPushController:(UIViewController *)pushedController{
    [_tab.selectedViewController.view setUserInteractionEnabled:NO];
}

-(void)pprevealSideViewController:(PPRevealSideViewController *)controller didPopToController:(UIViewController *)centerController{
        [_tab.selectedViewController.view setUserInteractionEnabled:YES];
    for (UIView *view in _tab.selectedViewController.view.subviews){
        if ([view isKindOfClass:[UIScrollView class]]){
            UIScrollView *sc=(UIScrollView*)view;
            [sc setScrollEnabled:YES];
        }
    }

}

#pragma mark - login success
-(void)login{
    
    //@用户信息
    NSUserDefaults * defaultData = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo=[defaultData objectForKey:@"personalInfo"];

    
    [constant setPersonalInfo:userInfo];
    [constant setName:userInfo[@"name"]];
    [constant setUserId:userInfo[@"userID"]];
    [constant setUserName:userInfo[@"userName"]];
    [constant setUserHeadUrl:userInfo[@"headUrl"]];
    [constant setIndexId:userInfo[@"id"]];
    [constant setBranch:userInfo[@"branch"]];
    //------------ Sakura-2014-10-09 begin 修改-------------
    [constant setPersonalScore:userInfo[@"personScore"]];
    //------------ Sakura end ---------------
    
    PioneerViewController *main = [[PioneerViewController alloc]init];
    CommunicationViewController *communicationViewController =[[CommunicationViewController alloc] init];
    PartyDataViewController *partyDataViewController = [[PartyDataViewController alloc]init];
    PersonalViewController *personalViewController =  [[PersonalViewController alloc]init];

    NSMutableDictionary *imgDic = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic setObject:[UIImage imageNamed:@"home.png"] forKey:@"Default"];
	[imgDic setObject:[UIImage imageNamed:@"home_highlighted.png"] forKey:@"Highlighted"];
	[imgDic setObject:[UIImage imageNamed:@"home_highlighted"] forKey:@"Seleted"];
    
    NSMutableDictionary *imgDic2 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic2 setObject:[UIImage imageNamed:@"file.png"] forKey:@"Default"];
	[imgDic2 setObject:[UIImage imageNamed:@"file_highlighted.png"] forKey:@"Highlighted"];
	[imgDic2 setObject:[UIImage imageNamed:@"file_highlighted"] forKey:@"Seleted"];
    
	NSMutableDictionary *imgDic3 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic3 setObject:[UIImage imageNamed:@"chat.png"] forKey:@"Default"];
	[imgDic3 setObject:[UIImage imageNamed:@"chat_highlighted.png"] forKey:@"Highlighted"];
	[imgDic3 setObject:[UIImage imageNamed:@"chat_highlighted"] forKey:@"Seleted"];

	NSMutableDictionary *imgDic4 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic4 setObject:[UIImage imageNamed:@"personal.png"] forKey:@"Default"];
	[imgDic4 setObject:[UIImage imageNamed:@"personal_highlighted.png"] forKey:@"Highlighted"];
	[imgDic4 setObject:[UIImage imageNamed:@"personal_highlighted.png"] forKey:@"Seleted"];
    NSArray *imgArr = [NSArray arrayWithObjects:imgDic,imgDic2,imgDic3,imgDic4,nil];
    
    NSArray *titleArray = @[@"资讯",@"微党课",@"交流",@"个人"];
    
    _tab = [[LeveyTabBarController alloc] initWithViewControllers:@[main,partyDataViewController,communicationViewController,personalViewController] imageArray:imgArr titles:titleArray];
    
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:_tab];
    nav.delegate=self;
    [nav.navigationBar setTranslucent:NO];
    [constant setCenterController:nav];
    _nav = nav;
    
    self.revealSideViewController = [[PPRevealSideViewController alloc] initWithRootViewController:nav];
    nav.revealSideViewController.delegate=self;
    LeftMenuTableViewController* leftVC = [[LeftMenuTableViewController alloc]init];
    [self.revealSideViewController preloadViewController:leftVC forSide:PPRevealSideDirectionLeft withOffset:70];
    
    [self.revealSideViewController setDirectionsToShowBounce:PPRevealSideDirectionNone];
    [self.revealSideViewController setPanInteractionsWhenClosed:PPRevealSideInteractionContentView | PPRevealSideInteractionNavigationBar];
    self.window.rootViewController = self.revealSideViewController;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    //远程推送所需信息
    NSDictionary *dic = [constant getPersonalInfo];
    NSString *branchNum = [dic objectForKey:@"branchNum"];
    NSString *instituteNum = [dic objectForKey:@"institute"];
    [BPush setTags:@[branchNum,instituteNum]];

}

#pragma mark - private
-(void)loginStateChange:(NSNotification *)notification
{
    
}

-(void)logout{
    LoginController *loginController  = [[LoginController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginController];
    nav.navigationBar.translucent=NO;
    self.window.rootViewController=nav;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
}

#pragma mark - navigationController delegate

-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if ([viewController isKindOfClass:[LeveyTabBarController class]]){
        LeveyTabBarController *v = (LeveyTabBarController*)viewController;
        [v.selectedViewController viewWillAppear:animated];
    }
}


- (void) showAlert: (NSString *) message
{
	UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [av show];
}

//- (NSString *)docFilePath {
//    NSString* s = [NSString stringWithFormat:@"%@/Documents/",NSHomeDirectory()];
//    return s;
//}
//
//- (NSString *)dataFilePath {
//    NSString* s = [NSString stringWithFormat:@"%@/Library/Caches/",NSHomeDirectory()];
//    return s;
//}
//
//- (NSString *)tempFilePath {
//    NSString* s = [NSString stringWithFormat:@"%@/tmp/",NSHomeDirectory()];
//    return s;
//}
//
//- (NSString *)imageFilePath {
//    NSString *s=[[NSBundle mainBundle] bundlePath];
//    s = [s stringByAppendingString:@"/"];
//    return s;
//}
//
//-(UIButton*)createFooterButton:(NSString*)s action:(SEL)action target:(id)target{
//    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.frame   = CGRectMake((320-76)/2, (49-36)/2, 152/2, 72/2);
//    btn.showsTouchWhenHighlighted = YES;
//    [btn setTitle:s forState:UIControlStateNormal];
//    btn.titleLabel.font = [UIFont systemFontOfSize:13];
//    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
//    return btn;
//}
//
//-(NSString*)formatdateFromStr:(NSString*)s format:(NSString*)str{
//    NSDateFormatter* f=[[NSDateFormatter alloc]init];
//    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate* d = [f dateFromString:s];
//    f.dateFormat = str;
//    NSString* s1 = [f stringFromDate:d];
//    return  s1;
//}
//
//-(NSString*)formatdate:(NSDate*)d format:(NSString*)str{
//    NSDateFormatter* f=[[NSDateFormatter alloc]init];
//    f.dateFormat = str;
//    NSString* s = [f stringFromDate:d];
//    return  s;
//}
//
//#pragma mark 发送 图片、音频 资源
//-(void)postSourceData:(NSData *) sourceData  sourcePath:(NSString *) sourcePath  mediaType:(NSString *)mediaType sourceName:(NSString *) sourceName{
//    
//    NSURL * sourceURL = [NSURL URLWithString:sourcePath];
//    NSMutableURLRequest *URLRequest = [[NSMutableURLRequest alloc]initWithURL:sourceURL
//                                                                  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
//                                                              timeoutInterval:TIMEOUT];
//    NSString *contentType = [NSString stringWithFormat:@"%@;boundary=%@",CONTENT_TYPE,BOUNDARY];
//    // 设置内容的类型 contentType,这完全是按照POST的格式来设置
//    [URLRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
//    [URLRequest setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
//    [URLRequest setHTTPMethod:@"POST"];
//    
//    NSMutableData *body = [NSMutableData data];
//    NSString *disposition = [[NSString alloc]init];
//    
//    // Add Body Prefix String
//    [body appendData:[[NSString stringWithFormat:@"%@%@%@",PREFIX,BOUNDARY,LINE_END] dataUsingEncoding:NSUTF8StringEncoding]];
//    if ([mediaType isEqualToString:@"1"]) {
//        disposition =
//        [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"%@", @"uploadimage", sourceName,LINE_END];
//    }else if ([mediaType isEqualToString:@"2"]){
//        disposition =
//        [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"%@", @"uploadvoice", sourceName,LINE_END];
//    }
//    [body appendData:[disposition dataUsingEncoding:NSUTF8StringEncoding]];
//    
//    NSString *bodyContentType = [NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"];
//    [body appendData:[bodyContentType dataUsingEncoding:NSUTF8StringEncoding]];
//    
//    [body appendData:sourceData];
//    
//    NSString *boundary = [NSString stringWithFormat:@"%@--%@--%@",LINE_END,BOUNDARY,LINE_END];
//    [body appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
//    [URLRequest setHTTPBody:body];
//    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:URLRequest delegate:self];
//    if (connection){
//        self.datas = [NSMutableData new];
//    }
//}
//
//#pragma mark 下载资源
//-(void) getSourceData:(NSString *)romotePath{
//    NSURL *url =[NSURL URLWithString:romotePath];
//    NSURLRequest *requst = [[NSURLRequest alloc] initWithURL:url];
//    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:requst
//                                                                   delegate:self startImmediately:YES];
//    if (connection!=nil) {
//        self.datas = [NSMutableData new];
//    }else{
//    }
//}
//
//-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//    [self.datas appendData:data];
//}
//
//-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
////    NSLog(@"出现错误了:%@",[error localizedDescription]);
//}
//
//-(void)connectionDidFinishLoading:(NSURLConnection*)connection{
////    NSLog(@"请求完成");
//    NSString * str = [[NSString alloc] initWithData:self.datas encoding:NSUTF8StringEncoding];
////    NSLog(@"转换完成str=%@",str);
//}
//
//////取得当前程序的委托
////-(AppDelegate *)appDelegate{
////    return (AppDelegate *) [[UIApplication sharedApplication] delegate];
////}
//
//未读消息有更新
-(void)notificationUnreadrefresh1:(NSNotification*)notify{
//    [self _initBarButton];
//        NSLog(@"notify.name = %@",notify.name);
    NSDictionary *dic;
//  NSLog(@"unread = %i",unread);
    if ([notify.name isEqualToString:@"NotificationUnreadChatMsgRefreshed"]) {
    
    if ([notify.object isEqualToString:@"highlighted"]){
            dic= @{@"Default":[UIImage imageNamed:@"chat_msg"],@"Highlighted":[UIImage imageNamed:@"chat_highlighted_msg"],@"Seleted":[UIImage imageNamed:@"chat_highlighted_msg"]};
    }else if([notify.object isEqualToString:@"normal"]){
            dic=@{@"Default":[UIImage imageNamed:@"chat"],@"Highlighted":[UIImage imageNamed:@"chat_highlighted"],@"Seleted":[UIImage imageNamed:@"chat_highlighted"]};
    }
        [_tab.leveyTabBarController setTabBarItemWithImageDicationary:dic ForIndex:2];
    }else if ([notify.name isEqualToString:kNotificationUnreadTotalRefreshed]) {
        //当前控制器是否有新值
        //    NSInteger unread= [Unread getUnreadNumWithKey:UnreadKey];
        NSInteger unread= [Unread getUnreadNumWithKey:kUnreadPioneerKey] + [Unread getUnreadNumWithKey:kUnreadPartyNoticeKey];
        //    NSInteger unread =[Unread getUnreadNumWithKey:kUnreadPioneerKey] + [Unread getUnreadNumWithKey:kUnreadPartyNoticeKey];
//        NSLog(@"[Unread getUnreadNumWithKey:kUnreadTotalKey] = %i",[Unread getUnreadNumWithKey:kUnreadTotalKey]);
//        NSLog(@"[Unread getUnreadNumWithKey:kUnreadPioneerKey] = %i",[Unread getUnreadNumWithKey:kUnreadPioneerKey]);
//        NSLog(@"[Unread getUnreadNumWithKey:kUnreadPartyNoticeKey] = %i",[Unread getUnreadNumWithKey:kUnreadPartyNoticeKey]);
//        NSLog(@"[Unread getUnreadNumWithKey:kUnreadPublicity] = %i",[Unread getUnreadNumWithKey:kUnreadPublicity]);
//        NSLog(@"[Unread getUnreadNumWithKey:kUnreadPartyActivity] = %i",[Unread getUnreadNumWithKey:kUnreadPartyActivity]);
//        NSLog(@"[Unread getUnreadNumWithKey:kUnreadMoodShare] = %i",[Unread getUnreadNumWithKey:kUnreadMoodShare]);
        
        
        NSDictionary *dic;
//        NSLog(@"unread = %i",unread);
        if (unread){
            dic= @{@"Default":[UIImage imageNamed:@"home_msg"],@"Highlighted":[UIImage imageNamed:@"home_highlighted_msg"],@"Seleted":[UIImage imageNamed:@"home_highlighted_msg"]};
        }
        else {
            dic=@{@"Default":[UIImage imageNamed:@"home"],@"Highlighted":[UIImage imageNamed:@"home_highlighted"],@"Seleted":[UIImage imageNamed:@"home_highlighted"]};
        }
        [_tab.leveyTabBarController setTabBarItemWithImageDicationary:dic ForIndex:0];
    }else if([notify.name isEqualToString:kLoginNotifaction]){
        NSDictionary *dic;
        dic=@{@"Default":[UIImage imageNamed:@"home"],@"Highlighted":[UIImage imageNamed:@"home_highlighted"],@"Seleted":[UIImage imageNamed:@"home_highlighted"]};
        [_tab.leveyTabBarController setTabBarItemWithImageDicationary:dic ForIndex:0];
        
    }

    
}

-(void)unreadChatMessageCountChange:(NSNotification*)notify{
    NSDictionary *dic;
    
    if (![notify.name isEqualToString:@"NotificationUnreadChatMsgRefreshed"]) {
        return;
    }
    
    if ([notify.object isEqualToString:@"highlighted"]){
        dic= @{@"Default":[UIImage imageNamed:@"chat_msg"],@"Highlighted":[UIImage imageNamed:@"chat_highlighted_msg"],@"Seleted":[UIImage imageNamed:@"chat_highlighted_msg"]};
    }else if([notify.object isEqualToString:@"normal"]){
        dic=@{@"Default":[UIImage imageNamed:@"chat"],@"Highlighted":[UIImage imageNamed:@"chat_highlighted"],@"Seleted":[UIImage imageNamed:@"chat_highlighted"]};
    }
    
    [_tab.leveyTabBarController setTabBarItemWithImageDicationary:dic ForIndex:2];
    
    [[NSUserDefaults standardUserDefaults] setObject:notify.userInfo[@"newMsg"]  forKey:@"newMsg"];
}


-(void)notificationUnreadrefresh:(NSNotification*)notify{
    
    NSDictionary *dic;
    
    if (![notify.name isEqualToString:@"NotificationUnreadChatMsgRefreshed"]) {
        return;
    }
    
    if ([notify.object isEqualToString:@"highlighted"]){
        dic= @{@"Default":[UIImage imageNamed:@"chat_msg"],@"Highlighted":[UIImage imageNamed:@"chat_highlighted_msg"],@"Seleted":[UIImage imageNamed:@"chat_highlighted_msg"]};
    }else if([notify.object isEqualToString:@"normal"]){
        dic=@{@"Default":[UIImage imageNamed:@"chat"],@"Highlighted":[UIImage imageNamed:@"chat_highlighted"],@"Seleted":[UIImage imageNamed:@"chat_highlighted"]};
    }
    
    [_tab.leveyTabBarController setTabBarItemWithImageDicationary:dic ForIndex:2];
    
    [[NSUserDefaults standardUserDefaults] setObject:notify.userInfo[@"newMsg"]  forKey:@"newMsg"];
   
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
//        UILocalNotification * notification = [[UILocalNotification alloc] init];
//        
//        //5秒钟之后触发
//        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.5];
//        
//        notification.alertBody =  @"来消息了";
//        notification.soundName = UILocalNotificationDefaultSoundName;
//        notification.applicationIconBadgeNumber = 100;
//        
//        notification.userInfo  = @{@"userName":@"梅花鹿",@"age":@18};
//        //要调用本地通知，需要通过UIApplication来统一调用
//        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}

-(void)ScreenTouch{

//    [Alert showAlert:@"屏幕触摸事件！"];
}

/******************************************环信相关函数start*******************************************************/
/******************************************环信相关函数start*******************************************************/
#pragma mark - IChatManagerDelegate 好友变化

- (void)didReceiveBuddyRequest:(NSString *)username
                       message:(NSString *)message
{
    if (!username) {
        return;
    }
    if (!message) {
        message = [NSString stringWithFormat:@"%@ 添加你为好友", username];
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":username, @"username":username, @"applyMessage":message, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleFriend]}];
    [[ApplyViewController shareController] addNewApply:dic];
    if (_comController) {
        [_comController setupUntreatedApplyCount];
    }
    
}

#pragma mark - IChatManagerDelegate 群组变化

- (void)didReceiveGroupInvitationFrom:(NSString *)groupId
                              inviter:(NSString *)username
                              message:(NSString *)message
{
    if (!groupId || !username) {
        return;
    }
    
    NSString *groupName = groupId;
    if (!message || message.length == 0) {
        message = [NSString stringWithFormat:@"%@ 邀请你加入讨论组\'%@\'", username, groupName];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":groupName, @"groupId":groupId, @"username":username, @"applyMessage":message, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleGroupInvitation]}];
    [[ApplyViewController shareController] addNewApply:dic];
    if (_comController) {
        [_comController setupUntreatedApplyCount];
    }
}

//接收到入群申请
- (void)didReceiveApplyToJoinGroup:(NSString *)groupId
                         groupname:(NSString *)groupname
                     applyUsername:(NSString *)username
                            reason:(NSString *)reason
                             error:(EMError *)error
{
    if (!groupId || !username) {
        return;
    }
    
    if (!reason || reason.length == 0) {
        reason = [NSString stringWithFormat:@"%@ 申请加入讨论组\'%@\'", username, groupname];
    }
    else{
        reason = [NSString stringWithFormat:@"%@ 申请加入讨论组\'%@\'：%@", username, groupname, reason];
    }
    
    if (error) {
        NSString *message = [NSString stringWithFormat:@"发送申请失败:%@\n原因：%@", reason, error.description];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
    else{
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":groupname, @"groupId":groupId, @"username":username, @"groupname":groupname, @"applyMessage":reason, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleJoinGroup]}];
        [[ApplyViewController shareController] addNewApply:dic];
        if (_comController) {
            [_comController setupUntreatedApplyCount];
        }
    }
}

- (void)didReceiveRejectApplyToJoinGroupFrom:(NSString *)fromId
                                   groupname:(NSString *)groupname
                                      reason:(NSString *)reason
{
    if (!reason || reason.length == 0) {
        reason = [NSString stringWithFormat:@"被拒绝加入讨论组\'%@\'", groupname];
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"申请提示" message:reason delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)group:(EMGroup *)group didLeave:(EMGroupLeaveReason)reason error:(EMError *)error
{
    NSString *tmpStr = group.groupSubject;
    NSString *str;
    if (!tmpStr || tmpStr.length == 0) {
        NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
        for (EMGroup *obj in groupArray) {
            if ([obj.groupId isEqualToString:group.groupId]) {
                tmpStr = obj.groupSubject;
                break;
            }
        }
    }
    
    if (reason == eGroupLeaveReason_BeRemoved) {
        str = [NSString stringWithFormat:@"你被从讨论组\'%@\'中踢出", tmpStr];
    }
    if (str.length > 0) {
        TTAlertNoTitle(str);
    }
}

#pragma mark - push

- (void)didBindDeviceWithError:(EMError *)error
{
    if (error) {
        TTAlertNoTitle(@"消息推送与设备绑定失败");
    }
}

/******************************************环信相关函数end*******************************************************/
/******************************************环信相关函数end*******************************************************/
@end
